package Concurrency.AsynTaskExecute;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 多线程的定时任务执行服务示例
 * 运行程序发现，第二个任务不会被第一个任务延迟
 * 因为在创建ScheduledExecutorService时，指定了Executors.newScheduleThreadPool的参数corePoolSize，因此timer里不只有1个线程
 */

public class SchduledFixedDelay {
    static class LongRunningTask implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("经过了5秒的运行后，LongRunningTask执行结束了");
        }
    }

    static class FixedDelayTask implements Runnable {
        static int count = 0;
        @Override
        public void run() {
            System.out.println(count++);
        }
    }

    public static void main(String[] args) {
        ScheduledExecutorService timer = Executors.newScheduledThreadPool(10);
        timer.schedule(new LongRunningTask(), 10, TimeUnit.MILLISECONDS);
        timer.scheduleWithFixedDelay(new FixedDelayTask(), 100, 1000, TimeUnit.MILLISECONDS);
    }
}
